<?php

namespace App\Http\Controllers\Api\Website;


use App\AreaBuild;
use App\Http\Resources\AreaCollection;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\BuildingCollection;
use App\Http\Resources\BuildingResource;
use App\Repository\BuildingRepository;
use App\BrowseRecords;
use App\model\Building;
use App\User;
use App\UserSearch;
use Carbon\Carbon;
use App\model\ImSet;

class BuildingController extends Controller
{
    //
    public function index(Request $request,BuildingRepository $buildingRepository){
        $buildList=$buildingRepository->getList($request);
        $user_id = auth('api')->id();
        if(isset($request['search_key'])&&$request['search_key']!=''&&isset($user_id)){
            $now = Carbon::now();
            UserSearch::updateOrCreate(['user_id'=>$user_id,'search_key'=>$request['search_key']],['updated_at'=>$now]);
        }
        return new BuildingCollection($buildList);
    }
    public function detail(BuildingRepository $buildingRepository,$id){
        $build=$buildingRepository->detail($id);
        $build['rent_count']=Building::where('park_id',$build['park_id'] ?? 0)->count('id') ;

        $user_id = auth('api')->id();
        $build['im_set']=ImSet::find(1);
        if(isset($user_id)){
            $builds = Building::find($id);
            $title = $builds->title;
            $logo = $builds->logo;
            $now = Carbon::now();
            BrowseRecords::updateOrCreate(['user_id'=>$user_id,'produce_id'=>$id,'type'=>2],
                ['user_name'=>User::find($user_id)->name,'title'=>$title,'logo'=>$logo,'updated_at'=>$now]);
        }
        return new BuildingResource($build);
    }
    public function area(){
       $areaBuild= AreaBuild::all();
       return new AreaCollection($areaBuild);
    }
}
